#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "NesInput.h"

NesInputInfoType g_typeNesInputInfo = {0};

void vNesInputInit(void)
{
    g_typeNesInputInfo.JOYPAD1 = 0;
    g_typeNesInputInfo.JOYPAD2 = 0;
}

void vNesInputByteSet(uint8_t ucChannle, uint8_t ucValue)
{
    if(ucChannle & NES_JOYPAD1)
        g_typeNesInputInfo.JOYPAD1 = ucValue;

    if(ucChannle & NES_JOYPAD2)
        g_typeNesInputInfo.JOYPAD2 = ucValue;
}

uint8_t ucNesInputByteGet(uint8_t ucChannle)
{
    return (ucChannle & NES_JOYPAD1) ? g_typeNesInputInfo.JOYPAD1 : g_typeNesInputInfo.JOYPAD2;
}

void vNesInputBitSet(uint8_t ucChannle, uint8_t ucValue)
{
    if(ucChannle & NES_JOYPAD1)
        g_typeNesInputInfo.JOYPAD1 |= ucValue;

    if(ucChannle & NES_JOYPAD2)
        g_typeNesInputInfo.JOYPAD2 |= ucValue;
}

void vNesInputBitReset(uint8_t ucChannle, uint8_t ucValue)
{
    if(ucChannle & NES_JOYPAD1)
        g_typeNesInputInfo.JOYPAD1 &= ~ucValue;

    if(ucChannle & NES_JOYPAD2)
        g_typeNesInputInfo.JOYPAD2 &= ~ucValue;
}

uint8_t ucNesInputBitGet(uint8_t ucChannle)
{
    uint8_t ucBool = 0;

    if(g_typeNesInputInfo.enable == 0)
    {
        /* 获取对应手柄的值 */
        if(ucChannle & NES_JOYPAD1)
        {
            /* 获取对应手柄的bit值 */
            ucBool |= (g_typeNesInputInfo.JOYPAD1 & g_typeNesInputInfo.offset1) ? 1 : 0;
            g_typeNesInputInfo.offset1 = (g_typeNesInputInfo.offset1 == 0x01) ? 0x80 : g_typeNesInputInfo.offset1 >> 1;
        }

        if(ucChannle & NES_JOYPAD2)
        {
            /* 获取对应手柄的bit值 */
            ucBool |= (g_typeNesInputInfo.JOYPAD2 & g_typeNesInputInfo.offset2) ? 1 : 0;
            g_typeNesInputInfo.offset2 = (g_typeNesInputInfo.offset2 == 0x01) ? 0x80 : g_typeNesInputInfo.offset2 >> 1;
        }
    }

    return ucBool;
}

void vNesInputReset(uint8_t ucValue)
{
    /* 重头开始依次发送 */
    g_typeNesInputInfo.offset1 = 0x80;
    g_typeNesInputInfo.offset2 = 0x80;
    g_typeNesInputInfo.enable = ucValue;
}

void vNesInputExec(uint8_t ucValue)
{
    switch(ucValue)
    {
        case 'w' : g_typeNesInputInfo.JOYPAD1 = NesInput_Up; break;
        case 's' : g_typeNesInputInfo.JOYPAD1 = NesInput_Down; break;
        case 'a' : g_typeNesInputInfo.JOYPAD1 = NesInput_Left; break;
        case 'd' : g_typeNesInputInfo.JOYPAD1 = NesInput_Right; break;
        case 'v' : g_typeNesInputInfo.JOYPAD1 = NesInput_Select; break;
        case 'b' : g_typeNesInputInfo.JOYPAD1 = NesInput_Start; break;
        case 'j' : g_typeNesInputInfo.JOYPAD1 = NesInput_A; break;
        case 'k' : g_typeNesInputInfo.JOYPAD1 = NesInput_B; break;

        default : break;
    }
}

NesInputInfoType *ptyeNesInputInfoGet(void)
{
    return &g_typeNesInputInfo;
}
